package com.javaio.demo.bio.client;

import java.io.*;
import java.net.Socket;
import java.util.Objects;

/**
 * 客户端主线程
 */
public class ChatClient {
    private final String TUICHU = "tuichu";
    private final String SERVER_IP = "127.0.0.1";
    private final int SERVER_PROT = 8888;

    /**
     * 客户端变量
     */
    private Socket socket;
    //从服务器接收消息
    private BufferedReader bufferedReader;
    //发送消息给服务器和转发
    private BufferedWriter bufferedWriter;

    /**
     * 发送消息给服务器
     */
    public void send(String msg) throws IOException {
        //通过socket.shutdownInput()关闭输出流 只会关闭流
        //在客户端或者服务端通过socket.shutdownOutput()都是单向关闭的，
        // 即关闭客户端的输出流并不会关闭服务端的输出流，所以是一种单方向的关闭流；
        //判断客户端的输出流有没有关闭  单项关闭不会影响到服务端的socket
        if (!socket.isOutputShutdown()) {
            bufferedWriter.write(msg + "\n");
            //write后接flush缓冲区
            bufferedWriter.flush();
        }
    }

    /**
     * 接收服务器消息
     */
    public String receive() throws IOException {
        String msg = null;
        //判断客户端的输入流有没有关闭  单项关闭不会影响到服务端的socket
        if (!socket.isInputShutdown()) {
            msg = bufferedReader.readLine();
        }
        return msg;
    }

    /**
     * 检查用户是否退出
     */
    public boolean  readyTuiChu(String  msg){
        //这里还要判断用户发送的是否是退出消息如果是则关闭它的消息连接
        return  TUICHU.equals(msg) ? true : false;
    }
    /**
     * 关闭该服务端
     */
    public synchronized void close(){
        //关闭没用的socket的资源 避免占用资源过多消耗
        if(!Objects.equals(null,bufferedWriter)){
            try {
                //bufferedWriter关闭 socket也会关闭
                bufferedWriter.close();
                System.out.println("socket");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("该socket资源关闭连接异常");
            }
        }
    }
    /**
     * 启动客户端
     */
    public void start(){
        try {
            //创建socket连接
            socket = new Socket(SERVER_IP,SERVER_PROT);
            //创建io流
            //输入流
            bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //输出流
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            // 副线程处理消息发送
            new Thread(new UserInputHandler(this)).start();
            //主线程用来和服务器建立连接以及监听其他用户发来的消息
            String msg = null;
            //接收服务器发送来的消息
            while ((msg = receive()) != null){
                //打印服务器的消息
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        chatClient.start();
    }

}